import { Category } from 'server/models/Category'
import { successResponse, errorResponse } from 'server/utils/response'

export default defineEventHandler(async () => {
  try {
    const categories = await Category.getAllCategories()
    
    // 计算统计数据
    const totalCategories = categories.length
    const activeCategories = categories.filter(c => c.status === 'active').length
    const totalProjects = categories.reduce((sum, c) => sum + (c.post_count || 0), 0)
    
    // 计算最近活动（最近7天内更新的分类数量）
    const now = new Date()
    const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
    const recentActivity = categories.filter(c => {
      if (!c.updated_at) return false
      const updatedDate = new Date(c.updated_at)
      return updatedDate >= sevenDaysAgo
    }).length

    const stats = {
      totalCategories,
      activeCategories,
      totalProjects,
      recentActivity
    }

    return successResponse(stats, '获取分类统计成功')
  } catch (error) {
    console.error('获取分类统计失败:', error)
    return errorResponse('获取分类统计失败', error instanceof Error ? error.message : '未知错误')
  }
})